#include <iostream>
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <cassert>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc,char *argv[],char *env[])
{
    if(argc!=3)
    {
        fprintf(stdout,"\n./servec_udp ip port\n\n");
        exit(1);
    }
    
    std::string ip=argv[1];
    uint16_t port=atoi(argv[2]);

    // 创建套接字
    int sock=socket(AF_INET,SOCK_DGRAM,0);

    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(port);
    server.sin_addr.s_addr=inet_addr(ip.c_str());

    socklen_t slen=sizeof(server);
    std::string message;

    char buff[1024];
    for(;;)
    {
        std::cout<<"请输入:";
        std::getline(std::cin,message);

        // 客服端发送请求后 
        sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,slen);
        // 获取服务端的响应
        ssize_t n=recvfrom(sock,(void *)buff,sizeof(buff)-1,0,nullptr,nullptr);
        assert(n>=0);
        buff[n]='\0';

        std::cout<<buff<<std::endl;
    }

    return 0;
}